import java.awt.Color;
import java.util.Iterator;

public class Conrad implements IPlayer{ 
  protected Color _color, _hisColor = null;
  protected IBoard _board;

  // Our worker thread that scouts for bestMove
  protected CScoutThread _scThr;
  // Tourney-limited gameclock (hundredths of seconds)
  protected final int _maxCSeconds = 95;
  // This needs to be public so child/worker thread can set it
  public Integer bestMove;

  public void beginTurn(){
    // find the opponent's colour if we havn't before (this should only
    // happen once in a tourney and we have no better places to trigger
    // for it -- joinBoard() might be called before the other player
    // has joined the board, and constructor is almost useless)
    if (_hisColor == null){
      Iterator pInfoItr = _board.getPlayers();
      _hisColor = ((IPlayerInfo)pInfoItr.next()).getColor();
      if(_hisColor == _color) _hisColor = ((IPlayerInfo)pInfoItr.next()).getColor();
    }

    bestMove = null;

    // Pass ourself to the scout thread; the scout thread will search
    // iteratively deeper, setting this.bestMove every time. We let it run
    // for as long as _maxSeconds, then destroy it.
    _scThr = new CScoutThread(this, _board, _color, _hisColor);
    _scThr.start();
    try{
      _scThr.join(10 * _maxCSeconds);
    }
    catch (InterruptedException ie){

//    try{
//      if (bestMove == null)
//        _scThr.join(20 * _maxCSeconds);
//    }
//    catch (InterruptedException i) {
//    }
//
//    this code ^^ is only for small values (< 15ish) of _maxCSeconds

    }
    finally{
      if (bestMove == null)
        System.out.println("Fuck, we don't have a move.");
    }
    _scThr.stop();
    _scThr = null;

    if (bestMove == 64)
      _board.pass(this);
    else
      if (!_board.placePiece(this, bestMove >> 3, bestMove & 7))
        _board.pass(this);
  }

  public void joinBoard(IBoard board, Color color){
    _board = board;
    _color = color;
  }

  public         Conrad(){                  }
  public void   endTurn(){                  }
  public Color getColor(){ return _color;   }
  public String getName(){ return "Conrad"; }
} 
